package sk.naive.talker.command;

import sk.naive.talker.*;
import sk.naive.talker.util.Utils;
import sk.naive.talker.persistence.PersistenceException;
import sk.naive.talker.props.PropertyStoreException;

import java.rmi.RemoteException;
import java.util.*;

/**
 *
 * @author <a href="mailto:virgo@naive.deepblue.sk">Richard "Virgo" Richter</a>
 * @version $Revision: 1.8 $ $Date: 2005/01/08 18:15:19 $
 */
public class Nameform extends AbstractSetCommand {
	public static final String UPROP_NAME_FORM_PREFIX = "lang.";
	public static final Set<String> settable;

	protected String setValue(String key, String value)
		throws RemoteException,
		PropertyStoreException,
		PersistenceException
	{
		String login = user.getLogin();
		if (key.equals(User.UPROP_NAME)) {
			if (!Utils.normalize(value).equals(login)) {
				throw new PropertyStoreException("Invalid name form");
			}
		}
		String base = login.substring(0, login.length() - 1);
		if (validNameForm(value, base)) {
			value = Utils.capitalizeFirst(value);
			user.set(key, value);
			return value;
		} else {
			throw new PropertyStoreException("Invalid name form");
		}
	}

	private boolean validNameForm(String value, String base) {
		return Utils.normalize(value).startsWith(base) && (value.length() <= (base.length() + 4));
	}

	protected Set<String> getValidValues(String key) throws RemoteException {
		return null;
	}

	protected String getValue(String key) throws RemoteException, PropertyStoreException {
		return (String) user.get(key);
	}

	protected Set<String> settable() {
		return settable;
	}

	static {
		Set<String> s = new LinkedHashSet<String>();
		s.add(User.UPROP_NAME);
		s.add(UPROP_NAME_FORM_PREFIX + "sk.gen");
		s.add(UPROP_NAME_FORM_PREFIX + "sk.dat");
		s.add(UPROP_NAME_FORM_PREFIX + "sk.aku");
		s.add(UPROP_NAME_FORM_PREFIX + "sk.loc");
		s.add(UPROP_NAME_FORM_PREFIX + "sk.ins");
		settable = Collections.unmodifiableSet(s);
	}
}
